import scala.io.{BufferedSource, Source}

object Demo22Implicit03 {
  def main(args: Array[String]): Unit = {
    // 隐式转换类
    // 读取文件

    val r1: ReadFileFromPath = new ReadFileFromPath("Scala/data/students.txt")
    r1.read.take(10).foreach(println)

    val r2: ReadFileFromPath = new ReadFileFromPath("Scala/data/words.txt")
    r2.read.take(3).foreach(println)

    val r3: ReadFileFromPath = new ReadFileFromPath("Scala/data/score.txt")
    r3.read.take(10).foreach(println)

    //    new ReadFileFromPath("Scala/data/subject.txt").read.take(3).foreach(println)
    "Scala/data/subject.txt".read.take(3).foreach(println)


    "Scala/data/students.txt".printNumLine(10)
    "Scala/data/score.txt".printNumLine(10)
    "Scala/data/subject.txt".printNumLine(2)
  }


  /**
   * 隐式转换类必须定义在object中
   * 该类的构造方法只能有且只有一个参数：path
   * 通过隐式转换可以让参数path所属的类型String自动获得该类定义的所有的方法
   */
  implicit class ReadFileFromPath(path: String) {

    var lines: List[String] = _

    def read: List[String] = {
      val bs: BufferedSource = Source
        .fromFile(path)
      val list: List[String] = bs.getLines().toList

      bs.close()
      lines = list
      lines
    }

    def printNumLine(cnt: Int): Unit = {
      this.read.take(cnt).foreach(println)
    }
  }
}



